#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os

peri_list = [ "SYSCTRL", "RCC", "FMC", "PMU", "TIM0", "TIM1", "TIM2", "WWDG", "LIN", "LEDCTRL", "ADCCTRL", "GPIO"] 

def get_peri_regs(src_fr):
    peri_reg_flag = 0
    peri_reg_dict = {}
    peri_name = ""
    peri_regs = ""

    line = src_fr.readline()
    while line:
        if "address start \\newline" in line:
            peri_name = line.split(" ")[0]
            peri_reg_flag = 1

        if "address end \\newline" in line:
            peri_reg_flag = 0
            peri_reg_dict[peri_name] = peri_regs
            peri_regs = ""
            
        if peri_reg_flag == 1 and "address start \\newline" not in line:
            peri_regs += line

        line = src_fr.readline()
    return peri_reg_dict

def insert_peri_regs(des_fw, peri_reg_dict):
    file_str = ""
    peri_name = ""
    # 0: normal; 1: periname; 2: registers
    peri_reg_status = 0

    line = des_fw.readline()
    while line:
        if peri_reg_status == 2 and ("\\section{" in line  or "\\subsection{" in line or "\\end{document}" in line or "\\newpage" in line):
            peri_reg_status = 0

        if peri_reg_status == 1 and ("\\subsection{Registers}" in line):
            file_str += line + peri_reg_dict[peri_name]
            peri_reg_status = 2

        if peri_reg_status == 0 and ("\\section{" in line):
            sector_name = line.split("}")[0].split("{")[1]
            if sector_name in peri_list:
                peri_reg_status = 1
                peri_name = sector_name

        if peri_reg_status != 2: 
            file_str += line

        line = des_fw.readline()
    
    des_fw.seek(0)
    des_fw.write(file_str)

if __name__ == "__main__":
    current_dir = os.getcwd()
    latex_reg_name = current_dir + "\\datasheet\\R2406_latex.tex"
    datasheet_name = current_dir + "\\datasheet\\datasheet.tex"

    # latex_reg_name = "R2406_latex.tex"
    # datasheet_name = "datasheet.tex"

    src_fr = open(latex_reg_name, 'r', encoding='utf-8')
    des_fw = open(datasheet_name, 'r+', encoding='utf-8')

    peri_reg_dict = get_peri_regs(src_fr)
    insert_peri_regs(des_fw, peri_reg_dict)

    src_fr.close()
    des_fw.close()
    print("Finish inserting latex registers.")
